package com.iwop.moto.utils.api.YunXin;

import com.alibaba.fastjson.JSON;
import com.iwop.moto.comm.Comm;
import com.iwop.moto.comm.CommUrl;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.utils.stringUtil.Base64;
import com.iwop.moto.utils.stringUtil.SequenceUtil;
import com.iwop.moto.utils.stringUtil.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @功能: 网易云信(IM)工具类
 * @日期: liuwb by 2016-10-24 20:29:00 create
 */
public class YunXinUtils {

    static Logger logger=Logger.getLogger(YunXinUtils.class);
    public static String sendHttpRequest(String url, List<NameValuePair> nvps){
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String appKey = Comm.YunXinAppKey;
        String appSecret = Comm.YunXinAppSecret;
        String nonce =  SequenceUtil.nextInt(10000,99999);//随机数
        String curTime = String.valueOf((new Date()).getTime() / 1000L);//时间轴
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
        try{
            // 设置请求的header
            httpPost.addHeader("AppKey", appKey);
            httpPost.addHeader("Nonce", nonce);
            httpPost.addHeader("CurTime", curTime);
            httpPost.addHeader("CheckSum", checkSum);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            HttpResponse response = httpClient.execute(httpPost);// 执行请求
            return new String(EntityUtils.toString(response.getEntity(), "utf-8"));
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String addIMUser(String sid, String nickname, String imgpath, String token){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid",sid));
        nvps.add(new BasicNameValuePair("name",nickname));
        if(!StringUtils.isEmpty(imgpath)){
            String imageUrl = uploadImage(imgpath);
            nvps.add(new BasicNameValuePair("icon", imageUrl));
        }
        nvps.add(new BasicNameValuePair("token", token));
        String result = YunXinUtils.sendHttpRequest(CommUrl.ADDIMUSER, nvps);
        return result;
    }

    public static String updateIMUser(SuperRecordModel superRecordModel, SuperRecordModel srm){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid",superRecordModel.getString("accid")));
        srm.put("im_accid",superRecordModel.getString("accid"));
        if(!StringUtils.isEmpty(superRecordModel.getString("icon"))){
            String imagePath = uploadImage(superRecordModel.getString("icon"));
            nvps.add(new BasicNameValuePair("icon", imagePath));
            srm.put("im_icon", imagePath);
        }
        if(!StringUtils.isEmpty(superRecordModel.getString("name"))){
            nvps.add(new BasicNameValuePair("name", superRecordModel.getString("name")));
            srm.put("im_name", superRecordModel.getString("name"));
        }
        if(!StringUtils.isEmpty(superRecordModel.getString("gender"))){
            String gender = superRecordModel.getString("gender");
            if(gender.equals("0")){
                gender="2";
            }else if(gender.equals("2")){
                gender="0";
            }
            nvps.add(new BasicNameValuePair("gender", gender));
            srm.put("im_gender", superRecordModel.getString("gender"));
        }
        if(!StringUtils.isEmpty(superRecordModel.getString("im_birth"))){
            nvps.add(new BasicNameValuePair("im_birth", superRecordModel.getString("im_birth")));
            srm.put("im_birth", superRecordModel.getString("im_birth"));
        }
        String result = YunXinUtils.sendHttpRequest(CommUrl.EDITIMUSER,nvps);
        return result;
    }

    public static void addFriend(String accid,String faccid){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid",accid));
        nvps.add(new BasicNameValuePair("faccid",faccid));
        nvps.add(new BasicNameValuePair("type", "1"));
        String result = YunXinUtils.sendHttpRequest(CommUrl.ADDFRIEND, nvps);
    }

    public static String uploadImage(String path){
        String[] split = path.split("moto-images");
        if(split!=null && split.length==2){
            String partUrl = split[1];
            String imagePaht = Comm.ROOT_PATH + partUrl;
            File file=new File(imagePaht);
            try {
                FileInputStream fileInputStream=new FileInputStream(file);
                byte[] bytes = input2byte(fileInputStream);
                String encode = Base64.encode(bytes);
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                nvps.add(new BasicNameValuePair("content",encode));
                String result = YunXinUtils.sendHttpRequest(CommUrl.UPLOADIMAGE, nvps);
                Map parse = (Map)JSON.parse(result);
                return (String)parse.get("url");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return path;
            } catch (IOException e) {
                e.printStackTrace();
                return path;
            }
        }else {
            logger.error("上传到云信的图片出错了："+path);
            return path;
        }
    }

    public static final byte[] input2byte(FileInputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    public static String updatePassword(String sid,String password){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid",sid));
        nvps.add(new BasicNameValuePair("token",password));
        String result = YunXinUtils.sendHttpRequest(CommUrl.UPDATEPASSWORD, nvps);
        return result;
    }

}
